import java.applet.*;
import java.awt.*;

public class RunningHorse extends Applet implements Runnable	{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Thread horseThread = null;

	int totalHorses;
	int raceDistance;
	RunHorse[] TheHorse;
	Image[] imgHorse;
	AudioClip MyAudio;

	int theWinner;
	private boolean bRaceFinished = false;
	private String WinnerMsg = "";

	public void init()	{
		totalHorses = Integer.parseInt(getParameter("TotalHorses"));
		raceDistance = Integer.parseInt(getParameter("RaceDistance"));
		horseThread = new Thread(this, "RunningHorse");
		horseThread.setPriority(Thread.NORM_PRIORITY + 5);

		TheHorse = new RunHorse[totalHorses];
		imgHorse = new Image[totalHorses];
		for (int i=0; i<totalHorses; i++)	{
			TheHorse[i] = new RunHorse(getParameter("Horse" + i), raceDistance);
			imgHorse[i] = getImage(getDocumentBase(), "Images/Horse" + i + ".gif");
		}

		MyAudio = getAudioClip(getDocumentBase(), "Audio/RunHorse.au");
	}

	public void run()	{
		// The thread to repaint the Applet
		boolean bSomeoneAlive;
		do	{
			repaint();
			bSomeoneAlive = false;
			for (int i=0; i<totalHorses; i++)
				bSomeoneAlive = bSomeoneAlive || TheHorse[i].isAlive();
		} while (bSomeoneAlive);

		// Show the message to tell who is the winner
		theWinner = 0;
		for (int i=0; i<totalHorses; i++)	{
			if (TheHorse[theWinner].getRaceTime() > TheHorse[i].getRaceTime())
				theWinner = i; 
		}

		WinnerMsg = "The Winner is " + TheHorse[theWinner].getName();
		bRaceFinished = true;

		MyAudio.stop();
	}

	public boolean mouseDown(Event evt, int x, int y)	{
		// When mouse click, enable all threads
		for (int i=0; i<totalHorses; i++)
			if (! TheHorse[i].isAlive()) TheHorse[i].start();
		if (! horseThread.isAlive())
			horseThread.start();

		MyAudio.loop();
		return true;
	}

	public void paint(Graphics g)	{
		// Show the message on top
		if (horseThread.isAlive())
			g.drawString("Go! Go! Racing Horses...", 5, 25);
		else
			g.drawString("Reload the page and click to play...", 5, 25);

		// Draw the racing field
		g.setColor(Color.yellow);
		g.fillRect(0, 100, raceDistance, totalHorses * 100);

		// Draw the Horses, name and line
		int i;
		int ThisX, ThisY;
		g.setColor(Color.black);
		for (i=0; i<totalHorses; i++)	{
			ThisX = TheHorse[i].getCurrentDistance();
			ThisY = (i+1)*100;
			g.drawImage(imgHorse[i], ThisX, ThisY, this);
			g.drawLine(0, ThisY+50, ThisX, ThisY+50);
			g.drawString(TheHorse[i].getName(), raceDistance+110, ThisY+50);
		}

		if (bRaceFinished)	{
			g.drawString(WinnerMsg, 5, 95);
			for (i=0; i<totalHorses; i++)	{
				g.drawString(String.valueOf(TheHorse[i].getRaceTime()),
						raceDistance+110, (i+1)*100+75);
			}
		}
	}
}
